package collecion.nexd.com.newnexdcollection.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import collecion.nexd.com.newnexdcollection.R;
import collecion.nexd.com.newnexdcollection.activity.IView.ICollectionActivity;
import collecion.nexd.com.newnexdcollection.adapter.SlidingMenuAdapter;
import collecion.nexd.com.newnexdcollection.modle.MallInfoObject;
import collecion.nexd.com.newnexdcollection.presenter.ICollectionImpl;
import collecion.nexd.com.newnexdcollection.presenter.IPresenter.ICollection;
import collecion.nexd.com.newnexdcollection.util.MediaScanner;
import collecion.nexd.com.newnexdcollection.util.ProgressDialogUtils;


public class CollectionActivity extends Activity implements AdapterView.OnItemSelectedListener, CompoundButton.OnCheckedChangeListener, ICollectionActivity {
    public static final int NOTIFYDATASETCHANGE = 1001;
    public static final int UPDATENVIRONMENTCOUNT = 1002;
    public static final int UPDATESTEP = 1003;
    public static final int SAVEOVER = 1004;
    public static final int LOADMALLINFOSUCCESS = 1005;
    public static final int CHANGUITOENABLE = 1006;
    public static final int CHANGEUITODISENABLE = 1007;
    public static final int TIME_INTERVAL = 1008;
//    public static final String DBNAME = "collection.db";

    private ICollection iCollection;
    // 采集频率数组
    private String[] arr_acquisition_cycles = new String[]{"500", "1000", "2000", "5000"};
    private String[] arr_c_city_name = new String[]{"天津"};
    private String[] arr_e_city_name = new String[]{"tianjin"};
    // 商场列表对象集合，解析XML后返回，主要为获取英文名
    private List<MallInfoObject> mallInfoObjectList;
    // 商场列表名称集合， 用来显示在Spinner上
    private ArrayList<String> cMallNameList;
    // spinner 数组
    ArrayAdapter<String> acquisition_cycles_adapter;
    ArrayAdapter<String> cityAdapter;
    ArrayAdapter<String> mallInfoAdapter;
    // View
    Spinner sp_city_name;
    Spinner sp_mall_name;
    EditText et_user_name;
    EditText et_floorId;
    Spinner sp_acquisition_cycles;
    TextView environment_data;
    TextView tv_step;
    ToggleButton tg_start_end_button;
    ImageView iv_animator;
    Timer timer;
    // SlidingMenu
    SlidingMenu slidingMenu;
    ListView lv_coll_data_name;
    // telephone Service
    TelephonyManager manager;
    private SlidingMenuAdapter slidingMenuAdapter;

    boolean bl_isStart = false;
    // 记录选择的采集频率
    String str_acquisition_cycles;
    String str_city_name;
    String str_mall_name;
    String str_mall_floor;
    String str_user_name;
    String str_telephone_imei;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NOTIFYDATASETCHANGE:
                    updateSlidingMenuData();
                    break;
                case UPDATENVIRONMENTCOUNT:
                    environment_data.setText(msg.obj.toString());
                    break;
                case UPDATESTEP:
                    Log.e("计步器返回的数值", msg.obj.toString());
                    tv_step.setText(String.valueOf(msg.obj));
                    break;
                case SAVEOVER:
                    iCollection.loadSlidilingMenuData(slidingMenuAdapter);
                    ProgressDialogUtils.dismissProgressDialog(CollectionActivity.this);
                    break;
                case LOADMALLINFOSUCCESS:
                    mallInfoAdapter.notifyDataSetChanged();
                    break;
                case CHANGEUITODISENABLE:
                    changeUIClickable(false);
                    break;
                case CHANGUITOENABLE:
                    changeUIClickable(true);
                    break;
                case TIME_INTERVAL:
                    Toast.makeText(CollectionActivity.this, "未采集到任何数据！", Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        setContentView(R.layout.activity_main);
        manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        iCollection = new ICollectionImpl(this, manager, this, handler);
        initView();
        initParam();
        initSlidingMenu();

        iCollection.initSDK();
        // drop adapter
        acquisition_cycles_adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, arr_acquisition_cycles);
        cityAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, arr_c_city_name);
        mallInfoAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, cMallNameList);
        sp_acquisition_cycles.setAdapter(acquisition_cycles_adapter);
        sp_city_name.setAdapter(cityAdapter);
        sp_mall_name.setAdapter(mallInfoAdapter);
        setClickListener();
        str_city_name = arr_e_city_name[0];
        iCollection.initDropList(str_city_name);
    }

    private void initParam() {
        timer = new Timer();
        mallInfoObjectList = new ArrayList<>();
        cMallNameList = new ArrayList<>();
        // 初始化设备信息
        str_telephone_imei = manager.getDeviceId().substring(manager.getDeviceId().length() - 4);
        iCollection.setCollectionMessageList(mallInfoObjectList, cMallNameList);
    }

    private void setClickListener() {
        sp_acquisition_cycles.setOnItemSelectedListener(this);
        sp_mall_name.setOnItemSelectedListener(this);
        sp_city_name.setOnItemSelectedListener(this);
        tg_start_end_button.setOnCheckedChangeListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && bl_isStart)
            return false;
        else if (keyCode == KeyEvent.KEYCODE_MENU && bl_isStart)
            return false;
        else {
            super.onKeyDown(keyCode, event);
            return true;
        }
    }

    private void initSlidingMenu() {
        slidingMenu = new SlidingMenu(this);
        slidingMenu.setMode(SlidingMenu.LEFT);
        // 设置触屏模式
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setShadowDrawable(R.drawable.shadow);
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        // 设置侧滑宽度
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        // 设置出入效果
        slidingMenu.setFadeDegree(0.35f);
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        // 为侧滑设置布局
        slidingMenu.setMenu(R.layout.sliding_list_view);
        lv_coll_data_name = (ListView) slidingMenu.findViewById(R.id.lv_coll_data_name);
        slidingMenuAdapter = new SlidingMenuAdapter(this);
        lv_coll_data_name.setAdapter(slidingMenuAdapter);
        iCollection.loadSlidilingMenuData(slidingMenuAdapter);
    }

    private void initView() {
        sp_city_name = (Spinner) this.findViewById(R.id.sp_city);
        sp_mall_name = (Spinner) this.findViewById(R.id.sp_mall_name);
        et_user_name = (EditText) this.findViewById(R.id.et_user_name);
        et_floorId = (EditText) this.findViewById(R.id.floorId);
        sp_acquisition_cycles = (Spinner) this.findViewById(R.id.sp_acquisition_cycles);
        tg_start_end_button = (ToggleButton) this.findViewById(R.id.tg_start_end_button);
        environment_data = (TextView) this.findViewById(R.id.environment_data);
        tv_step = (TextView) this.findViewById(R.id.tv_step_count);
        iv_animator = (ImageView) this.findViewById(R.id.iv_animator);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        switch (parent.getId()) {
            case R.id.sp_acquisition_cycles:
                str_acquisition_cycles = acquisition_cycles_adapter.getItem(position);
                Log.i(CollectionActivity.class.getSimpleName(), str_acquisition_cycles);
                break;
            case R.id.sp_city:
                break;
            case R.id.sp_mall_name:
                str_mall_name = mallInfoObjectList.get(position).geteMallName();
                Log.i(CollectionActivity.class.getSimpleName(), str_mall_name);
                break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            str_user_name = et_user_name.getText().toString().trim();
            str_mall_floor = et_floorId.getText().toString().trim();
            if (TextUtils.isEmpty(str_mall_name)) {
                tg_start_end_button.setChecked(false);
                showTipDialog(1);
                return;
            }
            if (TextUtils.isEmpty(str_user_name)) {
                tg_start_end_button.setChecked(false);
                showTipDialog(2);
                return;
            }
            if (TextUtils.isEmpty(str_acquisition_cycles)) {
                tg_start_end_button.setChecked(false);
                showTipDialog(3);
                return;
            }
            if (TextUtils.isEmpty(str_mall_floor)) {
                tg_start_end_button.setChecked(false);
                showTipDialog(4);
                return;
            }

            Log.i(CollectionActivity.class.getSimpleName(), "开始采集, 商场: " + str_mall_name + "采集人：" + str_user_name + ", 采集楼层: " + str_mall_floor);
            tv_step.setText("0");
            // 开始后，设置编辑框和下拉选择不可被编辑，防止修改数据。
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(CHANGEUITODISENABLE);
                }
            }, 1000);
            bl_isStart = true;
            // 设置动画
            iv_animator.setVisibility(View.VISIBLE);
            iv_animator.startAnimation(AnimationUtils.loadAnimation(CollectionActivity.this, R.anim.translate));
            iCollection.startCollection(str_acquisition_cycles, str_telephone_imei,str_city_name, str_mall_name, str_mall_floor, str_user_name); // 开始采集
        } else {
//            AlertDialog.Builder builder = new AlertDialog.Builder(CollectionActivity.this);// .setIcon(R.drawable.warning)
//            builder.setTitle("通知").setMessage("确定结束当前采集任务！")
//                    .setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
            ProgressDialogUtils.showProgressDialog(CollectionActivity.this, "正在存储文件...", "通知", false);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(CHANGUITOENABLE);
                }
            }, 2000);
            bl_isStart = false;
            iv_animator.setAnimation(null);
            iv_animator.setVisibility(View.INVISIBLE);
            iCollection.finishedCollection(str_city_name, str_mall_name, str_mall_floor, str_user_name, str_acquisition_cycles);
        }
    }

    /**
     * 启动判断输入参数，为空，不允许进行后面的活动，提示dialog
     *
     * @param type
     */
    private void showTipDialog(int type) {
        String mess = "";
        if (type == 1)
            mess = "您没有输入商场的名字。";
        else if (type == 2)
            mess = "您没有输入用户的名字。";
        else if (type == 3)
            mess = "您没有选择采集频率。";
        else if (type == 4)
            mess = "您没有输入楼层信息。";
        AlertDialog.Builder builder = new AlertDialog.Builder(this); //.setIcon(R.drawable.warning)
        builder.setTitle("通知").setMessage(mess)
                .setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        try {
//            iCollection.startScan();
//        } catch (IllegalAccessException e) {
//            StatService.reportException(CollectionActivity.this, e);
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaScanner.scanFolder(this, Environment.getExternalStorageDirectory().getPath() + "/Collector");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bl_isStart) {
            iCollection.stopCollection();
        }
    }

    @Override
    public void changeUIClickable(boolean state) {
        sp_mall_name.setEnabled(state);
        et_user_name.setEnabled(state);
        et_floorId.setEnabled(state);
        sp_city_name.setEnabled(state);
        sp_acquisition_cycles.setEnabled(state);
    }

    @Override
    public void updateSlidingMenuData() {
        slidingMenuAdapter.notifyDataSetChanged();
        Toast.makeText(CollectionActivity.this, R.string.sliding_notic, Toast.LENGTH_SHORT).show();
    }
}
